"""
Celery 应用实例

创建和配置 Celery 应用
"""

from celery import Celery
import sys
from pathlib import Path

# 处理导入路径
if __name__ == "__main__" or "." not in __name__:
    sys.path.insert(0, str(Path(__file__).parent.parent.parent))
    from stage2_advanced.chapter04_background_tasks.config import CeleryConfig
else:
    from .config import CeleryConfig


# ========== 创建 Celery 应用 ==========

celery_app = Celery("fastapi_tasks")

# 从配置类加载配置
celery_app.config_from_object(CeleryConfig)

# 自动发现任务
celery_app.autodiscover_tasks(["stage2_advanced.chapter04_background_tasks"])


# ========== Celery 信号（可选）==========

from celery.signals import task_prerun, task_postrun, task_failure

@task_prerun.connect
def task_prerun_handler(sender=None, task_id=None, task=None, args=None, kwargs=None, **extra):
    """任务执行前的钩子"""
    print(f"Task {task.name}[{task_id}] is starting...")


@task_postrun.connect
def task_postrun_handler(sender=None, task_id=None, task=None, args=None, kwargs=None, retval=None, state=None, **extra):
    """任务执行后的钩子"""
    print(f"Task {task.name}[{task_id}] completed with state: {state}")


@task_failure.connect
def task_failure_handler(sender=None, task_id=None, exception=None, args=None, kwargs=None, traceback=None, einfo=None, **extra):
    """任务失败的钩子"""
    print(f"Task {sender.name}[{task_id}] failed: {exception}")


if __name__ == "__main__":
    # 启动 Celery worker
    # celery -A celery_app worker --loglevel=info
    celery_app.start()

